import {beforeHttp,afterHttp} from '@/plugins/http/interceptor';
import $utils from '@/plugins/utils';
import mainMixin from '@/plugins/mixin';
let requestTask = null;
const {
    UtilTools,hideLoading,showLoading,showToast,getCurPage
} = $utils;

const http = opt => {
    opt = opt || {};
    opt.timeout = opt.timeout || 1000 * 60;
    opt.data = opt.data || {};
    opt.header = UtilTools.extend(opt.header || {});
    opt.method = opt.method ? opt.method.toUpperCase() : 'POST';
    return new Promise((resolve, reject) => {
        beforeHttp(opt).then(opt => {
            opt.header.loading = opt.header.loading || {};
            if (opt.header.loading.show == undefined) {
                opt.header.loading.show = true;
            }
            if (opt.header.loading.show) {
                showLoading({
                    'title': opt.header.loading.title || '拼命加载中...',
                    'mask': opt.header.loading.mask || true
                });
            }
            requestTask = uni.request({
                'url': opt.url,
                'method': opt.method,
                'data': opt.data,
                'header': opt.header,
                'dataType': opt.dataType || 'JSON',
                'timeout': opt.timeout,
                // #ifdef H5
                'withCredentials': true,
                // #endif
                // responseType:opt.responseType,
                success(result) {
				    // if (opt.header.loading.show) { hideLoading(); }
                    afterHttp(result).then(res => {
                        resolve(res);
                    }).catch(err => {
                        // showToast({'title': err || '请求失败'});
                        reject(err);
                    });
                },
                fail(err) {
                    // showToast({'title': err || '请求失败'});
                    reject(err);
                },
                complete(res) {
                    // if (requestTask) { requestTask.abort(); }
					if (opt.header.loading.show) { hideLoading(); }
                }
            });
        }).catch(err => {
            // showToast({'title': err || '请求失败'});
            reject(err);
        });
    });
};

http.install = Vue => {
    Vue.mixin(mainMixin);
    Vue.prototype.$http = http;
    Vue.prototype.$utils = $utils;
};


export default http;
